//1:加载对应模块
var express = require("express");
const bodyParser = require("body-parser");        //处理post请求
const cookieParser = require("cookie-parser");    //session
const expressSession = require("express-session");//session
const cors = require("cors");                      //cors

var pool = require('./pool');
//2:引用连接池
//3:创建express 对象
var app = express();
var hostName = '127.0.0.1';
var port = 8099;

//4:配置第三方模块
//4.1:配置跨域模块
//origin 允许来自哪个域名下跨域访问
app.use(cors({
    origin: ["http://127.0.0.1"],
    credentials: true
}));

//4.2:post  req.body.uname
app.use(bodyParser.urlencoded({ extended: false }));

app.use(cookieParser());
app.use(expressSession({
    resave: false,           //每次请求是否重新设置session
    saveUninitialized: true,//每次请求是否设置cookie
    secret: "iajan",       //https加密码传输，密钥
}));
//5:指定静态资源目录  public

// 跨域请求头
// app.all('*', function (req, res, next) {
//     res.header("Access-Control-Allow-Origin", "*");
//     res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
//     res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
//     res.header("X-Powered-By", ' 3.2.1')
//     res.header("Content-Type", "application/json;charset=utf-8");
//     next();
// });

app.get("/get", function (req, res) {
    console.log("请求url：", req.path)
    console.log("请求参数：", req.query)
    res.send("这是get请求");
})

app.post("/post", function (req, res) {
    console.log("请求参数：", req.body);
    var result = { code: 200, msg: "post请求成功" };
    res.send(result);
});

app.post("/getUser", function (req, res) {
    // console.log("请求参数：", req.body);

    var id = req.query.id
    //查
    // pool.query(sql, [id], function (err, result) {
    //     console.log(result);

    //     if (err) {
    //         console.log('[SELECT ERROR] - ', err.message);
    //         return;
    //     }

    //     res.send(
    //         {
    //             code: 200,
    //             msg: "post请求成功",
    //             body:req.body,
    //             query:req.query,
    //             list: result
    //         }
    //     );
    // });

    pool.getConnection((err, conn) => {
        if (err) throw err;
        //4:创建sql语句并且发送sql获取返回结果
        var sql = 'SELECT * FROM USER  WHERE id= ?';
        conn.query(sql, [id], (err, result) => {
            if (err) throw err;
            if (result.length > 0) {
                //获取uid值,保存session
                req.session.id = result[0].id;
                res.json({
                    code: 200,
                    msg: "post请求成功",
                    body: req.body,
                    query: req.query,
                    list: result
                });
            } else {
                res.json({ code: -3, msg: "用户名或密码有误" });
            }
            conn.release();
        });
        //5:返回 json
        //6如果登录保存 uid session
    });
});
app.post('/setUser',function(req,res){
    var username = req.query.username;
    var password=req.query.password;
    var reg = /^[a-z0-9]{3,12}$/i;
    if(!reg.test(username)){
       res.json({code:-1,msg:"用户名格式不正确"});
       return;
    }
    if(!reg.test(password)){
        res.json({code:-2,msg:"密码格式不正确"});
        return;
     }


    pool.getConnection((err, conn) => {
        if(err)throw err;
        var sql='INSERT INTO user (username,password) VALUES (?,?) '
        conn.query(sql,[username,password],(err,result)=>{
            if(err)throw err;
            res.json({code:1,result:result,msg:"创建用户名成功"});

            conn.release();
        });
    })
})

// pool.end();

app.listen(port, hostName, function () {
    console.log(`服务器运行在http://${hostName}:${port}`);
});